<template>
  <el-form v-model="searchForm" class="search-form">
    <el-input v-model="searchForm.name" placeholder="请输入变量名称"></el-input>
    <SvgIcon icon-class="ic_搜索" />
  </el-form>
  <div class="variable-add">
    <div class="btn-group">
      <el-button type="success" @click="handleAdd" class="btn-add">新增变量</el-button>
      <el-button plain>清理未使用变量</el-button>
    </div>
  </div>
  <div class="variable-wrapper">
    <el-collapse v-model="activeVariable">
      <el-collapse-item
        v-for="(item, index) in filteredGlobalVariables"
        :key="item.name"
        :title="item.name"
        :name="item.name"
      >
        <template #title>
          <div class="global-variable-item-title-wrapper">
            <span class="variable-name">{{ item.name }}</span>
            <span class="operation">
              <span class="count-used">暂未使用</span>
              <SvgIcon icon-class="ic_复制" @click="handleCopy(item, $event)" />
              <SvgIcon icon-class="ic_删除" @click="handleRemove(item.name, $event)" />
            </span>
          </div>
        </template>
        <GlobalVariableItem
          v-model:data="editorStore.globalVariables[index]"
          @variable-name-change="handleVariableNameChange"
        />
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script lang="ts" setup>
import GlobalVariableItem from './components/global-variable-item/index.vue';
import { messageUtil } from '@jl/element-plus/utils';
import { confirmAgain } from '@/utils';
import { useEditorStore } from '@/store/editor';

defineOptions({
  name: 'GlobalVariable',
});

const editorStore = useEditorStore();

const searchForm = ref({
  name: '',
});

const formData = ref({
  name: 'variable',
  description: '',
  type: 'string',
  value: '',
});

const activeVariable = ref<string[]>([]);

const filteredGlobalVariables = computed(() => {
  return editorStore.globalVariables.filter((o) => o.name.indexOf(searchForm.value.name) > -1);
});

/**
 * 重置变量
 */
const reset = () => {
  formData.value = {
    name: 'variable',
    description: '',
    type: 'string',
    value: '',
  };
};

/**
 * 计算复制的新变量名称
 * @param variableName
 */
const genCopiedVariableName = (variableName: string) => {
  const variablesWithSameName = editorStore.globalVariables.filter((o) =>
    new RegExp(`${variableName}(_\\d+)?$`).test(o.name)
  );
  let nextSequence = 0;
  variablesWithSameName.forEach((o) => {
    const sequence = o.name.split(variableName + '_')[1];
    if (sequence) {
      nextSequence = Math.max(nextSequence, +sequence + 1);
      return;
    }
    nextSequence = 1;
  });
  return nextSequence === 0 ? variableName : `${variableName}_${nextSequence}`;
};

/**
 * 添加变量
 */
const handleAdd = () => {
  const { name, description, type, value } = formData.value;
  editorStore.globalVariables.push({
    name: genCopiedVariableName(name),
    description,
    type,
    value,
  });
  reset();
};

/**
 * 复制变量
 * @param item - 被复制的变量
 */
const handleCopy = (item: any, e: MouseEvent) => {
  e.stopPropagation();
  const { name, description, type, value } = item;
  editorStore.globalVariables.push({
    name: genCopiedVariableName(`${name.trim()}_copy`),
    description,
    type,
    value,
  });
  messageUtil.success('变量复制成功');
};

/**
 * 删除变量
 */
const handleRemove = async (variableName: string, e: MouseEvent) => {
  e.stopPropagation();
  const yes = await confirmAgain(
    '删除变量',
    `删除后无法恢复, 确定删除变量 ${variableName} 吗?`,
    '',
    '',
    'dark'
  );
  if (!yes) {
    messageUtil.info('取消了删除操作');
    return;
  }

  const index = editorStore.globalVariables.findIndex((o) => o.name === variableName);
  if (index > -1) {
    editorStore.globalVariables.splice(index, 1);
  }
};

/**
 * 变量名称改变时 \
 * 保持折叠面板展开状态
 * @param newName
 * @param oldName
 */
const handleVariableNameChange = (newName: string, oldName: string) => {
  const index = activeVariable.value.findIndex((o) => o === oldName);
  if (index > -1) {
    activeVariable.value.splice(index, 1, newName);
  }
};
</script>

<style lang="less" scoped>
.el-collapse {
  border-top-color: rgba(255, 255, 255, 0.1);
  border-bottom-color: rgba(255, 255, 255, 0.1);
  :deep(.el-collapse-item__header) {
    color: #fff;
    background-color: transparent;
    border-bottom-color: rgba(255, 255, 255, 0.1);
    height: 60px;
    display: block;
    .el-collapse-item__arrow {
      display: none;
    }
    .global-variable-item-title-wrapper {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      color: #fff;
      position: relative;
    }
    .variable-name {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-right: 10px;
    }
    .operation {
      flex-shrink: 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      cursor: auto;
      .svg-icon {
        font-size: 20px;
        cursor: pointer;
      }
      .count-used {
        margin-right: 10px;
      }
    }
    // .count-used {
    //   position: absolute;
    //   bottom: -20px;
    //   left: 20px;
    //   font-size: 12px;
    // }
  }
  :deep(.el-collapse-item__wrap) {
    padding: 10px 0;
    color: #fff;
    background-color: transparent;
    border-bottom-color: rgba(255, 255, 255, 0.1);
    padding: 10px 20px 0;
  }
  :deep(.el-collapse-item__content) {
    padding-bottom: 0;
  }
}
.search-form {
  padding: 10px 20px;
  position: relative;
  .svg-icon {
    position: absolute;
    left: 28px;
    top: 17px;
    font-size: 18px;
  }
  :deep(.el-input) {
    .el-input__inner {
      padding-left: 20px;
    }
  }
}
.variable-add {
  height: 40px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding: 0 20px 10px;
}
.btn-group {
  display: flex;
  justify-content: space-between;
  .el-button {
    flex: 1;
    color: #fff;
    background: rgba(5, 96, 253, 0.3);
    border: 1px solid #0560fd;
    &.btn-add {
      background: #0560fd;
    }
    &:hover {
      opacity: 0.8;
    }
  }
}
.variable-wrapper {
  height: calc(100vh - 244px);
  overflow-y: auto;
  user-select: none;
}
</style>
